package com.bite.friend.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bite.common.core.constants.CacheConstants;
import com.bite.common.core.enums.ResultCode;
import com.bite.common.redis.service.RedisService;
import com.bite.common.security.exception.ServiceException;
import com.bite.friend.domain.question.Question;
import com.bite.friend.mapper.question.QuestionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class QuestionCacheManager {
    @Autowired
    private RedisService redisService;
    //redis里面可能没有数据，所以是找mysql,然后同步一下
    @Autowired
    private QuestionMapper questionMapper;
    public Long getListSize(){
        return redisService.getListSize(CacheConstants.QUESTION_LIST);
    }

    public void refreshCache() {
        List<Question> questionList=questionMapper.selectList(new LambdaQueryWrapper<Question>()
                .select(Question::getQuestionId)
                .orderByDesc(Question::getCreateBy));
        //假如ID里面为空
        if(CollectionUtil.isEmpty(questionList)){
            return;
        }
        //否则,对象是Question对象，最好存的时候，直接就是id,不然还要转化
        List<Long>questionIdList=questionList.stream().map(Question::getQuestionId).toList();
        //尾插法，从右侧插入的方法。
        redisService.rightPushAll(CacheConstants.QUESTION_LIST,questionIdList);
    }

    public Long preQuestion(Long questionId) {
        Long index=redisService.indexOfForList(CacheConstants.QUESTION_LIST,questionId);
        //index有可能是第一题，所以
        if(index==0){
            throw new ServiceException(ResultCode.FAILED_FIRST_QUESTION);
        }
       return redisService.indexForList(CacheConstants.QUESTION_LIST,index-1,Long.class);
    }

    public Long nextQuestion(Long questionId) {
        Long index=redisService.indexOfForList(CacheConstants.QUESTION_LIST,questionId);
        //index有可能是第一题，所以
        long lastIndex=getListSize()-1;
        if(index==lastIndex){
            throw new ServiceException(ResultCode.FAILED_LAST_QUESTION);
        }
        return redisService.indexForList(CacheConstants.QUESTION_LIST,index+1,Long.class);
    }
}
